package educar.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.LayoutManager;
import java.awt.Toolkit;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;

import educar.controllers.IController;
import educar.controllers.LoginController;
import educar.idioma.Locale;
import educar.listeners.ButtonListener;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import org.jvnet.substance.SubstanceLookAndFeel;
import javax.swing.JComboBox;
import javax.swing.border.TitledBorder;

public class LoginView implements IView {
	private JFrame jfWindow;
	JTextField tfUsername;
	JPasswordField pfPassword;

	public LoginView() {
		jfWindow = new JFrame();
		jfWindow.setIconImage(Toolkit.getDefaultToolkit().getImage(IView.class.getResource("/educar/media/educar-icon2.png")));
		//Segun la dimension de la pantalla (resolucion) Centro el Cartel de Login
		Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
		Point framePos=new Point((int)(screenSize.width)/2-200,(int)(screenSize.height)/2-150);
		jfWindow.setLocation(framePos);
		//Renombro el cartel
		jfWindow.setTitle("Educar - "+Locale.LOGIN);
		Container container = jfWindow.getContentPane();

		//Selecciono un skin por defecto
		defaultSkin();
		
		setupMainContainer(container);	


		jfWindow.pack();
		jfWindow.setVisible(true);
		jfWindow.setResizable(false);
		jfWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}

	/**
	 * Configura el contenedor de la ventana 
	 * @param container "contendor de la ventana principal"
	 */
	private void setupMainContainer(Container container) {
		container.setLayout((LayoutManager) new BoxLayout(jfWindow.getContentPane(), BoxLayout.Y_AXIS));

		((JComponent) container).setBorder(new EmptyBorder(10, 10, 10, 10));

		JLabel lblWelcome = new JLabel(Locale.WELCOME);
		lblWelcome.setAlignmentX(Component.CENTER_ALIGNMENT);
		lblWelcome.setFont(new Font("Serif", Font.BOLD, 16));
		lblWelcome.setBorder(new EmptyBorder(0, 10, 10, 10));
		container.add(lblWelcome);

		// Lay out the buttons from left to right.
		JLabel lblUserName = new JLabel(Locale.USER_NAME+" :  ");
		lblUserName.setHorizontalAlignment(SwingConstants.RIGHT);
		tfUsername = new JTextField(20);
		JPanel usernamePane = new JPanel();
		usernamePane.setLayout(new BorderLayout(0, 0));
		usernamePane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
		usernamePane.add(lblUserName,BorderLayout.CENTER);
		usernamePane.add(tfUsername,BorderLayout.LINE_END);
		container.add(usernamePane);

		// Lay out the buttons from left to right.
		JLabel lblPassword = new JLabel(Locale.PASSWORD+" :  ");
		lblPassword.setHorizontalAlignment(SwingConstants.RIGHT);
		pfPassword = new JPasswordField(20);
		JPanel passwordPane = new JPanel();
		passwordPane.setLayout(new BorderLayout(0, 0));
		passwordPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
		passwordPane.add(lblPassword,BorderLayout.CENTER);
		passwordPane.add(pfPassword,BorderLayout.LINE_END);
		container.add(passwordPane, BorderLayout.PAGE_END);

		JPanel buttonsPane = new JPanel();
		buttonsPane.setLayout(new BoxLayout(buttonsPane, BoxLayout.LINE_AXIS));
		JButton bLogin = new JButton(Locale.LOGIN);
		bLogin.setAlignmentX(Component.LEFT_ALIGNMENT);
		
		//Creo el Boton y como es una accion simple creo el listener al mismo tiempo
		JButton bExit = new JButton(Locale.EXIT);
		bExit.addActionListener(new ActionListener () {public void actionPerformed(ActionEvent e){System.exit(0);}});
		bExit.setAlignmentX(Component.RIGHT_ALIGNMENT);		
		
		
		//Agrego los Botones
		buttonsPane.add(bLogin);
		//Un separador entre los botones
		Component verticalStrut = Box.createVerticalStrut(20);
		verticalStrut.setMaximumSize(new Dimension(10, 20));
		buttonsPane.add(verticalStrut);
		buttonsPane.add(bExit);
		
		
		
		ButtonListener buttonListener = new ButtonListener();
		IController loginController = new LoginController();
		loginController.setView(this);
		buttonListener.associate(bLogin, loginController);
				
		JPanel SkinPanel = new JPanel();
		SkinPanel.setLayout(new BoxLayout(SkinPanel,BoxLayout.LINE_AXIS));
		SkinPanel.setBorder(new TitledBorder(null, "Select Skin", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		SkinPanel.add(skinSelector());
		
		JPanel ThemePanel = new JPanel();
		ThemePanel.setLayout(new BoxLayout(ThemePanel,BoxLayout.LINE_AXIS));
		ThemePanel.setBorder(new TitledBorder(null, "Select Theme", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		ThemePanel.add(themeSelector());
		
		
		container.add(SkinPanel, BorderLayout.PAGE_END);
		//container.add(ThemePanel, BorderLayout.PAGE_END);
	
		Component verticalStrut2 = Box.createVerticalStrut(10);
		verticalStrut2.setMaximumSize(new Dimension(10, 10));
		
		container.add(verticalStrut2,BorderLayout.PAGE_END);
		
		
		//agrego el panel de botones al final del cuadro principal
		container.add(buttonsPane, BorderLayout.PAGE_END);
	}
	
	
	public void present(String model) {
		JOptionPane.showMessageDialog(null, model," " + Locale.MESSAGE,1);
	}

	/**
	 * Retorna el usuario ingresado
	 * @return String "contiene el usuario"
	 */
	public String getUsername() {
		return tfUsername.getText().trim();
	}

	/**
	 * Retorna el password ingresado
	 * @return String "contiene el password"
	 */
	public String getPassword() {
		return new String(pfPassword.getPassword());
	}
	
	/**
	 * Cierra la ventana actual sin salir del programa
	 */
	public void close(){
		jfWindow.dispose();
	}
	
	/**
	 * Crear el selector de Skin
	 * @return JComboBox "con la lista de skins y el listener"
	 */
	private JComboBox skinSelector() {
		String [] lista = {"Default","BusinessBlueSteel","Autumn","BusinessBlackSteel","Business",
				"ChallengerDeep","CremeCoffee","Creme","EmeraldDusk","FieldOfWheat",
				"FindingNemo","GreenMagic","Magma","Mango","MistSilver","Moderate",
				"NebulaBrickWall","Nebula","OfficeBlue2007","OfficeSilver2007","RavenGraphiteGlass",
				"RavenGraphite","Raven","Sahara"};
		final JComboBox comboBox = new JComboBox(lista);		
		comboBox.setMinimumSize(new Dimension(150, 20));
		comboBox.setMaximumSize(new Dimension(150, 32767));
		
		comboBox.addItemListener(new ItemListener(){
			  public void itemStateChanged(ItemEvent ie){
				  String str = (String)comboBox.getSelectedItem();
				  if (str.equals("Default")) {
					  defaultSkin();
				  } else {
					  changeSkin(str);}
		  		}
			  });		
		return comboBox;
	}
	
	/**
	 * Crear el selector de themes
	 * @return JComboBox "con la lista de themes y el listener"
	 */
	private JComboBox themeSelector() {
		String [] lista = {"Default","Aqua","BarbyPink","BottleGreen","Brown","Charcoal","Creme","DarkViolet",
				"DesertSand","Ebony","JadeForest","LightAqua","LimeGreen","Negated","Olive","Orange",
				"Purple","Raspberry","Saturated","Sepia","SteelBlue","SunGlare","Sunset","Terracotta"};
		final JComboBox comboBox = new JComboBox(lista);		
		comboBox.setMinimumSize(new Dimension(150, 20));
		comboBox.setMaximumSize(new Dimension(150, 32767));
		
		comboBox.addItemListener(new ItemListener(){
			  public void itemStateChanged(ItemEvent ie){
				  String str = (String)comboBox.getSelectedItem();
				  changeTheme(str);}
			  });		
		return comboBox;
	}
	
	/**
	 * Funcion interna para cambiar el Skin
	 * @param nuevo "nombre del skin"
	 */
	private void changeSkin(String nuevo) {
		JFrame.setDefaultLookAndFeelDecorated(false);
		SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin."+nuevo+"Skin");
	}
	
	/**
	 * Funcion interna para cambiar el Skin
	 * @param nuevo "nombre del skin"
	 */
	private void defaultSkin() {
		JFrame.setDefaultLookAndFeelDecorated(false);
		SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.MistAquaSkin");
	}
	
	/**
	 * Funcion interna para camibar el theme
	 * @param nuevo "nombre del theme"
	 */
	private void changeTheme(String nuevo) {
		JFrame.setDefaultLookAndFeelDecorated(true);
		SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.Substance"+nuevo+"Theme");
	}
	
}
